import { createStore } from 'vuex'
import { courseApi, classApi, studentApi, experimentApi, reportApi } from '@/utils/api'

export default createStore({
  state: {
    classes: [],
    courses: [],
    students: [],
    experiments: [],
    reports: [],
    experimentStatistics: [],
    studentStatistics: [],
    visualizationData: null,
    reportDirectory: '',
    currentClass: null,
    currentCourse: null,
    loading: false,
    error: null
  },
  getters: {
    getClasses: state => state.classes,
    getCourses: state => state.courses,
    getStudents: state => state.students,
    getExperiments: state => state.experiments,
    getReports: state => state.reports,
    getExperimentStatistics: state => state.experimentStatistics,
    getStudentStatistics: state => state.studentStatistics,
    getVisualizationData: state => state.visualizationData,
    getReportDirectory: state => state.reportDirectory,
    getCurrentClass: state => state.currentClass,
    getCurrentCourse: state => state.currentCourse,
    isLoading: state => state.loading,
    getError: state => state.error,
    getStudentsByClass: state => classId => {
      return state.students.filter(student => student.classId === classId)
    }
  },
  mutations: {
    // 设置加载状态
    SET_LOADING(state, loading) {
      state.loading = loading
    },

    // 设置错误信息
    SET_ERROR(state, error) {
      state.error = error
    },

    // 班级相关
    SET_CLASSES(state, classes) {
      state.classes = classes
    },
    ADD_CLASS(state, classItem) {
      state.classes.push(classItem)
    },
    UPDATE_CLASS(state, updatedClass) {
      const index = state.classes.findIndex(c => c.id === updatedClass.id)
      if (index !== -1) {
        state.classes.splice(index, 1, updatedClass)
      }
    },
    DELETE_CLASS(state, classId) {
      state.classes = state.classes.filter(c => c.id !== classId)
    },

    // 课程相关
    SET_COURSES(state, courses) {
      state.courses = courses
    },
    ADD_COURSE(state, course) {
      state.courses.push(course)
    },
    UPDATE_COURSE(state, updatedCourse) {
      const index = state.courses.findIndex(c => c.id === updatedCourse.id)
      if (index !== -1) {
        state.courses.splice(index, 1, updatedCourse)
      }
    },
    DELETE_COURSE(state, courseId) {
      state.courses = state.courses.filter(c => c.id !== courseId)
    },

    // 学生相关
    SET_STUDENTS(state, students) {
      state.students = students
    },
    SET_EXPERIMENTS(state, experiments) {
      state.experiments = experiments
    },
    ADD_STUDENT(state, student) {
      state.students.push(student)
    },
    ADD_STUDENTS(state, students) {
      state.students = [...state.students, ...students]
    },
    UPDATE_STUDENT(state, updatedStudent) {
      const index = state.students.findIndex(s => s.id === updatedStudent.id)
      if (index !== -1) {
        state.students.splice(index, 1, updatedStudent)
      }
    },
    DELETE_STUDENT(state, studentId) {
      state.students = state.students.filter(s => s.id !== studentId)
    },
    IMPORT_STUDENTS(state, students) {
      state.students = [...state.students, ...students]
    },

    // 实验相关
    ADD_EXPERIMENT(state, experiment) {
      state.experiments.push(experiment)
    },
    UPDATE_EXPERIMENT(state, updatedExperiment) {
      const index = state.experiments.findIndex(e => e.id === updatedExperiment.id)
      if (index !== -1) {
        state.experiments.splice(index, 1, updatedExperiment)
      }
    },
    DELETE_EXPERIMENT(state, experimentId) {
      state.experiments = state.experiments.filter(e => e.id !== experimentId)
    },

    // 实验报告相关
    SET_REPORTS(state, reports) {
      state.reports = reports
    },
    ADD_REPORT(state, report) {
      state.reports.push(report)
    },
    DELETE_REPORT(state, reportId) {
      state.reports = state.reports.filter(r => r.id !== reportId)
    },

    // 统计相关
    SET_EXPERIMENT_STATISTICS(state, statistics) {
      state.experimentStatistics = statistics
    },
    SET_STUDENT_STATISTICS(state, statistics) {
      state.studentStatistics = statistics
    },
    SET_VISUALIZATION_DATA(state, data) {
      state.visualizationData = data
    },

    // 其他
    SET_REPORT_DIRECTORY(state, directory) {
      state.reportDirectory = directory
    },
    SET_CURRENT_CLASS(state, classItem) {
      state.currentClass = classItem
    },
    SET_CURRENT_COURSE(state, course) {
      state.currentCourse = course
    }
  },
  actions: {
    // 课程相关
    async fetchCourses({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await courseApi.getAllCourses()
        commit('SET_COURSES', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async fetchExperimentsByCourse({ commit }, courseId) {
      commit('SET_LOADING', true)
      try {
        const response = await experimentApi.getExperimentsByCourse(courseId)
        commit('SET_EXPERIMENTS', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message || '获取课程实验失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async createCourse({ commit }, courseData) {
      commit('SET_LOADING', true)
      try {
        console.log('Creating course with data:', courseData)
        const response = await courseApi.createCourse(courseData)
        console.log('Create course response:', response)
        commit('ADD_COURSE', response)
        return response
      } catch (error) {
        console.error('Error creating course:', error)
        commit('SET_ERROR', error.message || 'Failed to create course')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async updateCourse({ commit }, { id, courseData }) {
      commit('SET_LOADING', true)
      try {
        console.log('Updating course with ID:', id, 'and data:', courseData)
        const response = await courseApi.updateCourse(id, courseData)
        console.log('Update course response:', response)
        commit('UPDATE_COURSE', response)
        return response
      } catch (error) {
        console.error('Error updating course:', error)
        commit('SET_ERROR', error.message || 'Failed to update course')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async deleteCourse({ commit }, courseId) {
      commit('SET_LOADING', true)
      try {
        await courseApi.deleteCourse(courseId)
        commit('DELETE_COURSE', courseId)
        return courseId
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 班级相关
    async fetchClasses({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await classApi.getAllClasses()
        commit('SET_CLASSES', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async fetchClassesByCourse({ commit }, courseId) {
      commit('SET_LOADING', true)
      try {
        const response = await classApi.getClassesByCourse(courseId)
        commit('SET_CLASSES', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async createClass({ commit }, classData) {
      commit('SET_LOADING', true)
      try {
        console.log('Creating class with data:', classData)
        const response = await classApi.createClass(classData)
        console.log('Create class response:', response)
        commit('ADD_CLASS', response)
        return response
      } catch (error) {
        console.error('Error creating class:', error)
        commit('SET_ERROR', error.message || 'Failed to create class')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async updateClass({ commit }, { id, classData }) {
      commit('SET_LOADING', true)
      try {
        console.log('Updating class with ID:', id, 'and data:', classData)
        const response = await classApi.updateClass(id, classData)
        console.log('Update class response:', response)
        commit('UPDATE_CLASS', response)
        return response
      } catch (error) {
        console.error('Error updating class:', error)
        commit('SET_ERROR', error.message || 'Failed to update class')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async deleteClass({ commit }, classId) {
      commit('SET_LOADING', true)
      try {
        await classApi.deleteClass(classId)
        commit('DELETE_CLASS', classId)
        return classId
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 学生相关
    async fetchStudents({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await studentApi.getAllStudents()
        commit('SET_STUDENTS', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async fetchStudentsByClass({ commit }, classId) {
      commit('SET_LOADING', true)
      try {
        const response = await studentApi.getStudentsByClass(classId)
        commit('SET_STUDENTS', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message || '获取班级学生失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async createStudent({ commit }, studentData) {
      commit('SET_LOADING', true)
      try {
        const response = await studentApi.createStudent(studentData)
        commit('ADD_STUDENT', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async updateStudent({ commit }, { id, studentData }) {
      commit('SET_LOADING', true)
      try {
        const response = await studentApi.updateStudent(id, studentData)
        commit('UPDATE_STUDENT', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async deleteStudent({ commit }, studentId) {
      commit('SET_LOADING', true)
      try {
        await studentApi.deleteStudent(studentId)
        commit('DELETE_STUDENT', studentId)
        return studentId
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async importStudents({ commit }, { classId, file }) {
      commit('SET_LOADING', true)
      try {
        const response = await studentApi.importStudents(classId, file)
        commit('ADD_STUDENTS', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 实验相关
    async fetchExperiments({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await experimentApi.getAllExperiments()
        commit('SET_EXPERIMENTS', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },


    // 统计相关
    async fetchExperimentStatistics({ commit }, { classId, courseId }) {
      commit('SET_LOADING', true)
      try {
        const response = await reportApi.getExperimentStatistics(classId, courseId)
        commit('SET_EXPERIMENT_STATISTICS', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async fetchStudentStatistics({ commit }, { classId, courseId }) {
      commit('SET_LOADING', true)
      try {
        const response = await reportApi.getStudentStatistics(classId, courseId)
        commit('SET_STUDENT_STATISTICS', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async fetchVisualizationData({ commit }, { classId, courseId }) {
      commit('SET_LOADING', true)
      try {
        const response = await reportApi.getVisualizationData(classId, courseId)
        commit('SET_VISUALIZATION_DATA', response)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },



    // 报告分析相关
    setReportDirectory({ commit }, directory) {
      commit('SET_REPORT_DIRECTORY', directory)
    },
    // 选择目录 - 这个方法现在只是一个占位符
    // 实际的目录选择由 DirectoryBrowser 组件处理
    async selectDirectory({ commit }, path) {
      if (path) {
        // 如果提供了路径，直接使用
        commit('SET_REPORT_DIRECTORY', path)
        return {
          success: true,
          message: '目录选择成功',
          path: path
        }
      }

      // 否则返回一个空对象，让调用者知道需要打开目录选择对话框
      return {}
    },
    async scanReportDirectory({ commit }, { directoryPath }) {
      commit('SET_LOADING', true)
      try {
        try {
          // 尝试调用后端API扫描目录
          const response = await fetch('http://localhost:8088/api/reports/scan-directory', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            body: JSON.stringify({ directoryPath })
          })

          // 检查响应状态
          if (!response.ok) {
            console.error('扫描目录失败，状态码:', response.status);
            const text = await response.text();
            console.error('响应内容:', text);
            throw new Error(`扫描目录失败，状态码: ${response.status}`);
          }

          const contentType = response.headers.get('content-type');
          if (!contentType || !contentType.includes('application/json')) {
            console.error('响应不是JSON格式:', contentType);
            const text = await response.text();
            console.error('响应内容:', text);
            throw new Error('服务器返回的不是JSON格式');
          }

          const data = await response.json();
          console.log('扫描目录响应:', data);

          if (data.success) {
            return data.result
          } else {
            throw new Error(data.message || '扫描目录失败')
          }
        } catch (apiError) {
          console.warn('后端API调用失败，使用模拟数据:', apiError);

          // 使用模拟数据
          return {
            files: [
              { name: '实验1_2021001_张三.doc', path: `${directoryPath}/实验1_2021001_张三.doc` },
              { name: '实验2_2021001_张三.doc', path: `${directoryPath}/实验2_2021001_张三.doc` },
              { name: '实验1_2021002_李四.doc', path: `${directoryPath}/实验1_2021002_李四.doc` },
              { name: '实验报告_2021003_王五.doc', path: `${directoryPath}/实验报告_2021003_王五.doc` }
            ],
            exceptions: {
              invalidFormat: [
                {
                  name: '实验报告_2021003_王五.doc',
                  path: `${directoryPath}/实验报告_2021003_王五.doc`,
                  reason: '文件名格式不正确',
                  parsedInfo: {
                    experimentName: '实验报告',
                    studentId: '2021003',
                    studentName: '王五'
                  }
                }
              ],
              unknownStudent: [
                {
                  name: '实验1_2021004_赵六.doc',
                  path: `${directoryPath}/实验1_2021004_赵六.doc`,
                  reason: '学生不存在',
                  parsedInfo: {
                    experimentName: '实验1',
                    studentId: '2021004',
                    studentName: '赵六'
                  }
                }
              ]
            }
          };
        }
      } catch (error) {
        console.error('扫描目录错误:', error);
        commit('SET_ERROR', error.message || '扫描目录失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async renameFile({ commit }, { oldPath, newName }) {
      commit('SET_LOADING', true)
      try {
        try {
          // 尝试调用后端API重命名文件
          const response = await fetch('http://localhost:8088/api/reports/rename-file', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            body: JSON.stringify({ oldPath, newName })
          })

          // 检查响应状态
          if (!response.ok) {
            console.error('重命名文件失败，状态码:', response.status);
            const text = await response.text();
            console.error('响应内容:', text);
            throw new Error(`重命名文件失败，状态码: ${response.status}`);
          }

          const contentType = response.headers.get('content-type');
          if (!contentType || !contentType.includes('application/json')) {
            console.error('响应不是JSON格式:', contentType);
            const text = await response.text();
            console.error('响应内容:', text);
            throw new Error('服务器返回的不是JSON格式');
          }

          const data = await response.json();
          console.log('重命名文件响应:', data);

          if (data.success) {
            return data.result
          } else {
            throw new Error(data.message || '重命名文件失败')
          }
        } catch (apiError) {
          console.warn('后端API调用失败，使用模拟数据:', apiError);

          // 使用模拟数据
          return {
            oldPath: oldPath,
            newPath: oldPath.replace(/[^/\\]+$/, newName),
            newName: newName
          };
        }
      } catch (error) {
        console.error('重命名文件错误:', error);
        commit('SET_ERROR', error.message || '重命名文件失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async scanAndAnalyzeReports({ commit }, { classId, courseId, directoryPath }) {
      commit('SET_LOADING', true)
      try {
        try {
          // 尝试调用后端API分析报告
          const response = await fetch('http://localhost:8088/api/reports/analyze', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            body: JSON.stringify({ classId, courseId, directoryPath })
          })

          // 检查响应状态
          if (!response.ok) {
            console.error('分析报告失败，状态码:', response.status);
            const text = await response.text();
            console.error('响应内容:', text);
            throw new Error(`分析报告失败，状态码: ${response.status}`);
          }

          const contentType = response.headers.get('content-type');
          if (!contentType || !contentType.includes('application/json')) {
            console.error('响应不是JSON格式:', contentType);
            const text = await response.text();
            console.error('响应内容:', text);
            throw new Error('服务器返回的不是JSON格式');
          }

          const data = await response.json();
          console.log('分析报告响应:', data);

          if (data.success) {
            return data.result
          } else {
            throw new Error(data.message || '分析报告失败')
          }
        } catch (apiError) {
          console.warn('后端API调用失败，使用模拟数据:', apiError);

          // 使用模拟数据
          return {
            experimentStatistics: [
              {
                experimentName: '实验1',
                totalStudents: 30,
                submittedCount: 25,
                missingCount: 5,
                submissionRate: 0.83,
                missingStudents: [
                  { id: '1', studentId: '2021005', name: '赵六' },
                  { id: '2', studentId: '2021006', name: '钱七' },
                  { id: '3', studentId: '2021007', name: '孙八' },
                  { id: '4', studentId: '2021008', name: '周九' },
                  { id: '5', studentId: '2021009', name: '吴十' }
                ]
              },
              {
                experimentName: '实验2',
                totalStudents: 30,
                submittedCount: 28,
                missingCount: 2,
                submissionRate: 0.93,
                missingStudents: [
                  { id: '1', studentId: '2021005', name: '赵六' },
                  { id: '2', studentId: '2021006', name: '钱七' }
                ]
              }
            ],
            studentStatistics: [
              {
                studentId: '2021001',
                name: '张三',
                missingCount: 0,
                totalCount: 2,
                submissionRate: 1.0,
                missingExperiments: []
              },
              {
                studentId: '2021005',
                name: '赵六',
                missingCount: 2,
                totalCount: 2,
                submissionRate: 0.0,
                missingExperiments: [
                  { id: '1', name: '实验1' },
                  { id: '2', name: '实验2' }
                ]
              }
            ]
          };
        }
      } catch (error) {
        console.error('分析报告错误:', error);
        commit('SET_ERROR', error.message || '分析报告失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 其他
    setCurrentClass({ commit }, classItem) {
      commit('SET_CURRENT_CLASS', classItem)
    },
    setCurrentCourse({ commit }, course) {
      commit('SET_CURRENT_COURSE', course)
    },
    setClasses({ commit }, classes) {
      commit('SET_CLASSES', classes)
    },
    setCourses({ commit }, courses) {
      commit('SET_COURSES', courses)
    },
    addClass({ commit }, classItem) {
      commit('ADD_CLASS', classItem)
    },
    addCourse({ commit }, course) {
      commit('ADD_COURSE', course)
    }
  },
  modules: {}
})
